package com.todod.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchRestClient {

	// ES地址
	@Value("${elasticsearch.ip}")
	private String ip;
	@Value("${elasticsearch.userName}")
	private String userName;
	@Value("${elasticsearch.password}")
	private String password;

	@Bean
	public RestClientBuilder restClientBuilder() {
		RestClientBuilder builder = RestClient.builder(makeHttpHost());
		// 简单的身份认证
		final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

		builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				// 线程设置
				httpClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(10).build());
				return httpClientBuilder;
			}
		});
		return builder;
	}

	@Bean
	public RestHighLevelClient restHighLevelClient(RestClientBuilder restClientBuilder) {
		return new RestHighLevelClient(restClientBuilder);
	}
	
	public static RestHighLevelClient getrestHighLevelClient(RestClientBuilder restClientBuilder) {
		return new RestHighLevelClient(restClientBuilder);
	}

	private HttpHost[] makeHttpHost() {
		String[] ips = ip.split(",");
		HttpHost[] array = new HttpHost[ips.length];
		for (int i = 0; i < ips.length; i++) {
			String[] hostPort = ips[i].split(":");
			if (hostPort.length != 2) {
				throw new RuntimeException("elasticsearch.ip配置异常");
			}
			String host = hostPort[0];
			int port = Integer.parseInt(hostPort[1]);
			HttpHost httpHost = new HttpHost(host, port, "http");

			array[i] = httpHost;
		}
		return array;
	}
}